/* 
* Copyright (C) 2010, John Asmuth

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
* 
*  $Revision$
*  $Date$
*  $Author$
*  $HeadURL$
* 
*/

package rlglue

import (
	"errors"
	"fmt"
)

type Experiment struct {
	nw *network
}

func (ex *Experiment) Connect(host string, port int) (err error) {
	ex.nw = new(network)
	if err = ex.nw.Connect(host, port); err != nil {
		return
	}
	ex.nw.ClearSendBuffer()
	ex.nw.PutInt(kExperimentConnection)
	ex.nw.PutInt(0)
	err = ex.nw.Send()
	return
}

func (ex *Experiment) AutoConnect() (err error) {
	host, port := GetEnvHostPort()
	err = ex.Connect(host, port)
	return
}

func (ex *Experiment) Close() error {
	return ex.nw.Close()
}

func (ex *Experiment) doCallWithNoParams(state int32) (err error) {
	ex.nw.ClearSendBuffer()
	ex.nw.PutInt(state)
	ex.nw.PutInt(0)
	err = ex.nw.Send()
	return
}

func (ex *Experiment) doStandardRecv(expectedState int32) (err error) {
	ex.nw.ClearRecvBuffer()
	recvSize, err := ex.nw.Recv(2 * kIntSize)
	if err != nil {
		return
	}
	recvSize -= 2 * kIntSize

	glueState, err := ex.nw.GetInt()
	if err != nil {
		return
	}
	dataSize, err := ex.nw.GetInt()
	if err != nil {
		return
	}
	remaining := dataSize - recvSize

	if remaining < 0 {
		remaining = 0
	}

	if _, err = ex.nw.Recv(remaining); err != nil {
		return
	}

	if glueState != expectedState {
		err = errors.New(fmt.Sprintf("Not synced with server. Expected state %d, got %d", expectedState, glueState))
		return
	}

	return
}

func (ex *Experiment) Init() (taskString string, err error) {
	if err = ex.doCallWithNoParams(kRLInit); err != nil {
		return
	}
	if err = ex.doStandardRecv(kRLInit); err != nil {
		return
	}
	taskString, err = ex.nw.GetString()
	return
}

func (ex *Experiment) Start() (obs Observation, act Action, err error) {
	if err = ex.doCallWithNoParams(kRLStart); err != nil {
		return
	}
	if err = ex.doStandardRecv(kRLStart); err != nil {
		return
	}
	obs, err = ex.nw.GetObservation()
	if err != nil {
		return
	}
	act, err = ex.nw.GetAction()
	return
}

func (ex *Experiment) Step() (obs Observation, act Action, r float64, t bool, err error) {
	if err = ex.doCallWithNoParams(kRLStep); err != nil {
		return
	}
	if err = ex.doStandardRecv(kRLStep); err != nil {
		return
	}
	ti, err := ex.nw.GetInt()
	t = ti == 1
	if err != nil {
		return
	}
	r, err = ex.nw.GetDouble()
	if err != nil {
		return
	}
	obs, err = ex.nw.GetObservation()
	if err != nil {
		return
	}
	act, err = ex.nw.GetAction()
	return
}

func (ex *Experiment) Cleanup() (err error) {
	if err = ex.doCallWithNoParams(kRLCleanup); err != nil {
		return
	}
	err = ex.doStandardRecv(kRLCleanup)
	return
}

func (ex *Experiment) AgentMessage(message string) (reply string, err error) {
	ex.nw.ClearSendBuffer()
	ex.nw.PutInt(kRLAgentMessage)
	ex.nw.PutInt(int32(len(message)) + kIntSize)
	ex.nw.PutString(message)
	if err = ex.nw.Send(); err != nil {
		return
	}
	ex.doStandardRecv(kRLAgentMessage)
	reply, err = ex.nw.GetString()
	return
}

func (ex *Experiment) EnvironmentMessage(message string) (reply string, err error) {
	ex.nw.ClearSendBuffer()
	ex.nw.PutInt(kRLEnvMessage)
	ex.nw.PutInt(int32(len(message)) + kIntSize)
	ex.nw.PutString(message)
	if err = ex.nw.Send(); err != nil {
		return
	}
	ex.doStandardRecv(kRLEnvMessage)
	reply, err = ex.nw.GetString()
	return
}

func (ex *Experiment) Return() (r float64, err error) {
	if err = ex.doCallWithNoParams(kRLReturn); err != nil {
		return
	}
	if err = ex.doStandardRecv(kRLReturn); err != nil {
		return
	}
	r, err = ex.nw.GetDouble()
	return
}

func (ex *Experiment) NumSteps() (numSteps int32, err error) {
	if err = ex.doCallWithNoParams(kRLNumSteps); err != nil {
		return
	}
	if err = ex.doStandardRecv(kRLNumSteps); err != nil {
		return
	}
	numSteps, err = ex.nw.GetInt()
	return
}

func (ex *Experiment) NumEpisodes() (numEpisodes int32, err error) {
	if err = ex.doCallWithNoParams(kRLNumEpisodes); err != nil {
		return
	}
	if err = ex.doStandardRecv(kRLNumEpisodes); err != nil {
		return
	}
	numEpisodes, err = ex.nw.GetInt()
	return
}

func (ex *Experiment) Episode(numSteps int32) (exitStatus int32, err error) {
	ex.nw.ClearSendBuffer()
	ex.nw.PutInt(kRLEpisode)
	ex.nw.PutInt(kIntSize)
	ex.nw.PutInt(numSteps)
	if err = ex.nw.Send(); err != nil {
		return
	}
	if err = ex.doStandardRecv(kRLEpisode); err != nil {
		return
	}
	exitStatus, err = ex.nw.GetInt()
	return
}
